package com.framework.validated.advice;

import com.framework.validated.common.R;
import com.framework.validated.exception.ExceptionEnum;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        HashMap<String, String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(ExceptionEnum.DATA_VALIDATED_ERROR, map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e) {
        // e.getClass()：获取异常类,全路径名
        return R.error(e.getClass() + ":" + e.getMessage());
    }
}
